<?php
namespace App\Wen\Utils;

use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Jobs\Circle\UpdateCircleCountJob;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxTag;
use App\Models\Posts\WxUserCircle;
use App\Models\Circle\WxCircleTag;
use App\Models\User\WxUser;
use App\Models\User\WxUserFinancial;
use App\Models\User\WxUserVisit;
use App\Models\WxIcon;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class CircleUtils{


    public static function user_can_publish(&$user, $circle, $process_pay = false){
        $res = ['code'=>1, 'tip'=>''];

        if(_empty_($user) || _empty_($circle)){
            $res['code'] = 0;
            $res['tip'] = '参数错误';
            return $res;
        }

        if(UserUtils::is_mini_admin($user['id']) || UserUtils::is_player_admin()){
            return $res;
        }


        $is_publish_follow = $circle->is_publish_follow;
        $is_publish_vip = $circle->is_publish_vip;
        $is_publish_authentication = $circle->is_publish_authentication;
        $is_publish_admin = $circle->is_publish_admin;
        $is_publish_pay = $circle->is_publish_pay;

        $_tip = '';
        $flag = false;

        if($is_publish_follow == 1){
            $flag = true;
            $is_follow_circle = WxCircleRepositores::isFollowCircle($user['id'], $circle->id);
            if($is_follow_circle){
                $res['tip'] = '使用[已关注用户]发布权限';
                return $res;
            }
            if($_tip){
                $_tip .= '，[已关注用户]';
            }else{
                $_tip .= '[已关注用户]';
            }
        }
        if($is_publish_vip == 1){
            $flag = true;
            if($user['is_member']){
                $res['tip'] = '使用[会员]发布权限';
                return $res;
            }
            if($_tip){
                $_tip .= '，[会员]';
            }else{
                $_tip .= '[会员]';
            }
        }

        if($is_publish_authentication == 1){
            $flag = true;
            if($user['is_authentication']){
                $res['tip'] = '使用[认证用户]发布权限';
                return $res;
            }
            if($_tip){
                $_tip .= '，[认证用户]';
            }else{
                $_tip .= '[认证用户]';
            }
        }

        if($is_publish_admin == 1){
            $flag = true;
            if(UserUtils::is_mini_admin($user['id'])){
                $res['tip'] = '使用[管理员]发布权限';
                return $res;
            }
            if($_tip){
                $_tip .= '，[管理员]';
            }else{
                $_tip .= '[管理员]';
            }
        }

        if($is_publish_pay == 1){
            $flag = true;
            $publish_pay_num = $circle->publish_pay_num;
            $publish_pay_credit = $circle->publish_pay_credit;
            if($publish_pay_credit == 1){
                // 余额支付
                $wd = WxUserFinancial::where('user_id', $user['id'])->first();
                if(_empty_($wd)){
                    $res['code'] = 200012;
                    $res['tip'] = '余额不足！请前往我的钱包充值';
                    return $res;
                }
                if($wd['balance'] - $publish_pay_num < 0){
                    $res['code'] = 200012;
                    $res['tip'] = '余额不足！请前往我的钱包充值';
                    return $res;
                }
                if($process_pay){
                    $pay_res = UserUtils::update_user_financial($user['id'], 9, $publish_pay_num, '您消费了'.$publish_pay_num.'余额在「'.'<a href="/pages/circle/list?id='.$circle->id.'">'.$circle->circle_name.'</a>'.'」圈子发布一篇内容。');
                    if($pay_res){
                        $res['tip'] = '消费了'.$publish_pay_num.'余额';
                        return $res;
                    }
                }else{
                    return $res;
                }
            }else{
                //金币支付
                $coins = UserUtils::user_coins($user['id']);
                if($coins - $publish_pay_num < 0){
                    $res['code'] = 200011;
                    $res['tip'] = Settings::get('app_coin_name', '硬币').'不足！';
                    return $res;
                }
                if($process_pay){
                    $pay_res = UserUtils::update_user_coins($user['id'],6, -$publish_pay_num, '消费'.$publish_pay_num.Settings::get('app_coin_name', '硬币').'在「'.$circle->circle_name.'」圈子发布一篇内容。');
                    if($pay_res){
                        $res['tip'] = '消费了'.$publish_pay_num.Settings::get('app_coin_name', '硬币');
                        return $res;
                    }
                }else{
                    return $res;
                }
            }
            if($_tip){
                $_tip .= '，[付费按次发布]';
            }else{
                $_tip .= '[付费按次发布]';
            }
        }

        if($flag){
            $res['code'] = 0;
            $res['tip'] = '仅' . $_tip . '拥有发布权限';
            return $res;
        }

        return $res;

    }


    public static function circle_filter($is_tenant, $follow, $tags, $orderBy, $order, $master){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        if(!in_array($follow, [0, 1, 2])){
            return null;
        }
        if(!in_array($orderBy, ['created_at', 'last_publish_at', 'last_enter_at', 'total_post_count', 'total_comment_count', 'follow_at', 'count_circle_follow', 'count_pay_content'])){
            return null;
        }
        if(!in_array($order, ['desc', 'asc'])){
            return null;
        }
        if(_empty_($tags)){
            $tags = [];
        }
        $query = WxCircle::where('id', '>', 0);
        if($is_tenant){
            $query = $query->where(function ($query) {
                global $__MINI_GLOBAL_TENANT_ID__;
                $query->where('tenant_show', -1)
                    ->orWhere('tenant_show', $__MINI_GLOBAL_TENANT_ID__);
            });
        }
        if($master == 1){
            $query = $query->where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__);
        }

        // 处理follow
        if($follow == 1){
            if($orderBy == 'follow_at'){
                $circle_ids = WxUserCircle::where([['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__], ['user_circle_state', '=', 0]])->orderBy('updated_at', 'desc')->pluck('circle_id')->toArray();
                $query->whereIn('id', $circle_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $circle_ids) . '"' . ")"), $order);
            }else{
                $circle_ids = WxUserCircle::where([['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__], ['user_circle_state', '=', 0]])->orderBy('updated_at', 'desc')->pluck('circle_id')->toArray();
                $query = $query->whereIn('id', $circle_ids);
            }
        }else if($follow == 2){
            $circle_ids = WxUserCircle::where([['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__], ['user_circle_state', '=', 0]])->orderBy('updated_at', 'desc')->pluck('circle_id')->toArray();
            $query->whereNotIn('id', $circle_ids);
        }

        // 处理tag
        if($tags){
            $circle_ids = WxCircleTag::whereIn('tag_id', $tags)->orderBy('times', 'desc')->pluck('circle_id')->toArray();
            $query = $query->whereIn('id', $circle_ids);
        }

        if(in_array($orderBy, ['created_at', 'last_publish_at','last_enter_at', 'count_circle_follow', 'count_pay_content', 'total_post_count', 'total_comment_count'])){
            // 变种orderBy
            if($orderBy == 'total_post_count'){
                $query = $query->orderBy('count_circle_posts', $order);
            }else if($orderBy == 'total_comment_count'){
                $query = $query->orderBy('count_comment', $order);
            }else if($orderBy == 'count_circle_follow'){
                $query = $query->orderBy('count_circle_follow', $order);
            }else if($orderBy == 'count_pay_content'){
                $query = $query->orderBy('count_pay_content', $order);
            }else if($orderBy == 'created_at'){
                $query = $query->orderBy('created_at', $order);
            }else if($orderBy == 'last_publish_at'){
                $query = $query->orderBy('last_publish_at', $order);
            }else if($orderBy == 'last_enter_at'){
                $object_ids = WxUserVisit::where([['user_id','=', $__MINI_GLOBAL_CURRENT_USER_ID__],['type', '=', 2]])->orderBy('updated_at', $order)->limit(100)->pluck('object_id');
                if($object_ids) {
                    $query = $query->whereIn('id', $object_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $object_ids->toArray()) . '"' . ")"));
                }
            }
        }

        if(false){

        }else{
            $query = $query->where('circle_state', 1);
        }

        $data = $query->simplePaginate(10);
        if($data){
            $data->map(function ($v) use ($__MINI_GLOBAL_CURRENT_USER_ID__){
                $v->can_i_visit = CircleUtils::can_i_visit($v, $__MINI_GLOBAL_CURRENT_USER_ID__);
                $v->is_dot = !UserUtils::is_user_readed_circle($__MINI_GLOBAL_CURRENT_USER_ID__, $v->id);
                $v->user_circle_count = self::circleFollowCount($v->id);
            });
        }


        return $data;
    }

    /**
     * 添加圈子-话题 引用统计
     * @param $circle_id
     * @param $tagsIds 数组
     * @return null
     */
    public static function add_circle_tags($circle_id, $tagsIds){
        if(_empty_($circle_id) && $circle_id > 0 || _empty_($tagsIds)){
            return null;
        }
        foreach ($tagsIds as $tag_id){
            $circle_tag = WxCircleTag::where([
                ['circle_id', '=', $circle_id],
                ['tag_id', '=', $tag_id]
            ])->first();
            if($circle_tag){
                WxCircleTag::where([
                    ['circle_id', '=', $circle_id],
                    ['tag_id', '=', $tag_id]
                ])->increment('times');
            }else{
                $model = new WxCircleTag();
                $model->circle_id = $circle_id;
                $model->tag_id = $tag_id;
                $model->times = 1;
                $model->save();
            }
        }
    }


    /**
     * 圈子的关注人数
     */
    public static function circleFollowCount($circle_id)
    {
        if(_empty_($circle_id)){
            return null;
        }
        return (int)(Cache::remember('circle:followCount:'.$circle_id, 600, function () use ($circle_id){
            $followCount = WxUserCircle::where('circle_id',$circle_id)->where('user_circle_state', 0)->count();
            return $followCount;
        }));
    }


    public static function circleFollowUsers($circle_id){
        if(_empty_($circle_id)){
            return null;
        }
        return Cache::remember('circle:follow:users:'.$circle_id, 3600, function () use ($circle_id){
            $userIds = WxUserCircle::where('circle_id', $circle_id)->where('user_circle_state', 0)->orderBy('created_at', 'desc')->limit(5)->pluck('user_id');
            if($userIds){
                return WxUser::whereIn('id', $userIds)->get(['id', 'user_name', 'user_avatar']);
            }
            return null;
        });
    }

    public static function is_list_waterfall($circle_id){
        if(_empty_($circle_id)){
            return null;
        }

        $res = (int)(Cache::remember('circle:list:style:'.$circle_id, 3600, function () use ($circle_id){
            $list_style = WxCircle::where('id', $circle_id)->value('list_style');
            if( $list_style == 2 ){
                return 2;
            }else if($list_style == 0 && Settings::get('app_circle_list_style', 0, true) == 1){
                return 0;
            }else{
                return 1;
            }
        }));

        if($res == 2){
            return true;
        }

        $user_setting_style = mini_current_user(2, 'diy_scene_6_post_list_style');
        if($user_setting_style){
            if($user_setting_style != 1){
                if($user_setting_style == 3){
                    return true;
                }else{
                    return false;
                }
            }else{
                if($res === 0){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            if($res === 0){
                return true;
            }else{
                return false;
            }
        }
    }

    public static function circle_tags($circle_id){
        if(_empty_($circle_id)){
            return null;
        }
        $tags = WxTag::whereIn('id', function ($query) use ($circle_id) {
            $query->select('tag_id')
                ->from('wx_circle_tag')
                ->where('circle_id', $circle_id)
                ->orderByDesc('times');
        })->limit(10)->get(['id', 'tags_name']);
        if($tags->isEmpty()){
            return [];
        }else{
            return $tags;
        }
    }


    public static function sticky_notice_list($circle_id){
        if(_empty_($circle_id)){
            return null;
        }
        $sticky_notice_posts = get_circle_meta($circle_id, 'sticky_notice_list', 'j');
        if($sticky_notice_posts){
            $posts = WxPost::whereIn('id', $sticky_notice_posts)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $sticky_notice_posts) . '"' . ")"))->get(['id', 'posts_content']);
            if($posts->isEmpty()){
                return null;
            }

            $posts = $posts->map(function ($post){
                $posts_content = _mini_phone(_mini_emoji(_mini_aite_replace($post->posts_content), true), true);
                if($posts_content){
                    $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
                    $s_content =trim_all_space(strip_tags(html_entity_decode($s_content)), true);
                }
                $post->post_title = PostUtils::get_the_title($s_content, $post->id);
                return $post;
            });
            return $posts;
        }
    }


    public static function circle_square_list($circle){
        if(_empty_($circle)){
            return null;
        }
        $square_list = _empty_default_(explode(',', Settings::get('app_circle_square_list', '', true)), []);

        $circle_square_list = [];
        if($circle->square_list){
            if(StrUtils::startsWith($circle->square_list, '[')){
                $circle_square_list = json_decode(_empty_default_($circle->square_list, '[]'), true);
            }else{
                $circle_square_list = explode(',', _empty_default_($circle->square_list, ''));
            }
        }
        if(_empty_($circle_square_list)){
            $circle_square_list = [];
        }
        $last_square_list = array_merge($square_list, $circle_square_list);
        if(_empty_($last_square_list)){
            return null;
        }
        return WxIcon::whereIn('id', $last_square_list)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $last_square_list) . '"' . ")"))->get();
    }


    /**
     * @param WxCircle $circle
     * @param $uid
     * @return int -1:无意义 0：无限制 1：有权限 2：需解锁
     */
    public static function can_i_visit(WxCircle $circle, $uid){
        if(_empty_($circle)){
            return -1;
        }
        if(_empty_($uid)){
            if($circle->is_follow_vip == 1 || $circle->is_follow_authentication == 1 || $circle->is_follow_pay == 1){
                return 2;
            }else{
                return -1;
            }
        }
        if($circle->user_id == $uid){
            return 0;
        }
        $user = UserUtils::get_cached_user($uid);
        if(_empty_($user)){
            if($circle->is_follow_vip == 1 || $circle->is_follow_authentication == 1 || $circle->is_follow_pay == 1){
                return 2;
            }else{
                return -1;
            }
        }
        $flag = false;
        if($circle->is_follow_vip == 1 && $user['is_member']){
            $flag = true;
            return 1;
        }
        if($circle->is_follow_authentication == 1 && $user['is_authentication']){
            $flag = true;
            return 1;
        }
        if($circle->is_follow_pay == 1){
            $flag = true;
            $is_exists = WxUserCircle::where('user_id', $uid)->where('circle_id', $circle->id)->where('payment_duration', '>=', Carbon::now())->exists();
            if($is_exists){
                return 1;
            }
        }

        if($flag){
            return 2;
        }else{
            if($circle->is_follow_vip == 1 || $circle->is_follow_authentication == 1 || $circle->is_follow_pay == 1){
                return 2;
            }
            return 0;
        }

    }


    public static function circle_pass(WxCircle &$circle, $flag = 1, $overrule_content = ''){
        $is_need_notice = false;
        if($circle->circle_state === 0){
            $is_need_notice = true;
        }
        if($flag == 1){
            WxCircle::where('id',$circle->id)->update([
                'circle_state'=> 1
            ]);
            if($is_need_notice){
                UserUtils::add_user_notice(5001, $circle->user_id, '圈子审核通知', '您的创建的圈子已经审核通过啦', 100);
            }
        }else if($flag == 2){
            WxCircle::where('id',$circle->id)->update([
                'circle_state'=> 2
            ]);
            UserUtils::add_user_notice(5001, $circle->user_id, '圈子审核通知', '您的创建的圈子被驳回了' . (!_empty_($overrule_content) ? ('，驳回原因：' . $overrule_content) : ''), 100);
        }
        Cache::forget('total:todo:count');
        Cache::forget('total:tenant:todo:count');
    }


}
